<template>
    <div class="main">
        <!-- 团购头部 -->
        <div>
            <el-space wrap :size="10">
                <el-input v-model="searchData.groupTitle" clearable placeholder="请输入商品名称" />
                <el-input v-model="searchData.groupId" clearable placeholder="请输入团购ID" />
                <el-select v-model="searchData.groupStatus" placeholder="请选择用户状态" style="width: 10vw;" clearable
                    @clear="searchData.groupStatus = undefined">
                    <el-option :label="item.label" :value="item.value" v-for="item in groupStatus" :key="item.value" />
                </el-select>
                <el-button type="primary" :icon="Search" @click="handlerSearch">查找</el-button>
                <el-button type="primary" :icon="Plus" @click="handlerAddCoupon">添加</el-button>
            </el-space>
        </div>
        <div class="conten">
            <!-- 团购列表 -->
            <div>
                <el-table :data="tableData" border style="width: 100%">
                    <el-table-column type="expand">
                        <template #default="props">
                            <el-descriptions :column="1" border>
                                <el-descriptions-item label="类目ID">
                                    <span>{{ props.row.categoryId }}</span>
                                </el-descriptions-item>
                                <el-descriptions-item label="商品sku属性">
                                    <el-table :data="groupShopSkuDTOList" border>
                                        <el-table-column label="SkuId" prop="id" align="center" />
                                        <el-table-column label="规格标题" prop="title" align="center" />
                                        <el-table-column label="团购价格(元)" prop="skuGroupShopPrice" align="center" />
                                        <el-table-column label="库存" prop="stock" align="center">
                                            <template #default="scope">
                                                <span>{{ scope.row.stock }}({{ props.row.unit }})</span>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="原始价格(元)" prop="originalPrice" align="center" />
                                        <el-table-column label="售卖价格(元)" prop="price" align="center" />
                                        <el-table-column label="会员价格(元)" prop="vipPrice" align="center" />
                                        <el-table-column label="国际条码" prop="barCode" align="center" />
                                    </el-table>
                                </el-descriptions-item>
                            </el-descriptions>

                        </template>
                    </el-table-column>
                    <el-table-column label="团购ID" prop="id" align="center" />
                    <el-table-column label="商品ID" prop="spuId" align="center" width="110" />
                    <el-table-column label="商品名称" prop="title" align="center" width="500" />
                    <el-table-column label="商品主图" prop="spuId" align="center" width="110">
                        <template #default="scope">
                            <el-popover trigger="hover" placement="right" width="300px">
                                <template #default>
                                    <div style="display: flex;justify-content: center;">
                                        <el-image style="width: 100%; height: 100%" :src="scope.row.img" />
                                    </div>
                                </template>
                                <template #reference>
                                    <div>
                                        <el-image style="width: 100px;height: 50px;" :src="scope.row.img"
                                            fit="contain" />
                                    </div>
                                </template>
                            </el-popover>
                        </template>
                    </el-table-column>
                    <el-table-column label="未满策略" prop="automaticRefund" align="center" width="110">
                        <template #default="scope">
                            <el-tag :type="scope.row.automaticRefund == 0 ? 'warning' : 'success'">
                                {{ scope.row.automaticRefund == 0 ? '发货' : '退款' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="活动状态" prop="status" align="center" width="110">
                        <template #default="scope">
                            <el-tag :type="scope.row.status == 0 ? 'danger' : ''">
                                {{ scope.row.status == 0 ? '冻结' : '激活' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="开始时间" prop="gmtStart" align="center" width="180">
                        <template #default="scope">
                            {{ new Date(scope.row.gmtStart).formate('yyyy-MM-dd hh:mm:ss') }}
                        </template>
                    </el-table-column>
                    <el-table-column label="结束时间" prop="gmtEnd" align="center" width="180">
                        <template #default="scope">
                            {{ new Date(scope.row.gmtEnd).formate('yyyy-MM-dd hh:mm:ss') }}
                        </template>
                    </el-table-column>
                    <el-table-column label="当前人数" prop="buyerNum" align="center" width="110" />
                    <el-table-column label="目标人数" prop="minNum" align="center" width="110" />
                    <el-table-column label="操作" align="center" width="200">
                        <template #default="scope">
                            <template v-if="scope.row.status == 0">
                                <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                                <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
                            </template>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 创建和编辑对话框 -->
            <div>
                <el-drawer v-model="visible" :show-close="false" direction="ltr" :size="800">
                    <template #header="{ close, titleId, titleClass }">
                        <h4 :id="titleId" :class="titleClass"> {{ bool == true ? '创建' : '编辑' }}团购商品</h4>
                        <el-button @click="visible = false">取消</el-button>
                        <el-button type="primary" @click="hedlerCreateAndEdit(ruleFormRef)">
                            {{ bool == true ? '创建' : '编辑' }}
                        </el-button>
                    </template>
                    <div class="conten-goodsSku">
                        <h4>商品属性(sku)</h4>
                        <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" class="demo-ruleForm"
                            label-position="left">
                            <el-form-item label="团购商品" prop="spuId" placeholder="团购商品" label-width="150px">
                                <el-cascader v-model="ruleForm.spuId" :options="options" :props="props" clearable
                                    @change="loadGroupShopSkuList" />
                            </el-form-item>
                            <el-form-item label="团购时间" prop="gmtEnd" label-width="150px">
                                <el-date-picker v-model="ruleForm.gmtStart" type="datetime" placeholder="选择日期"
                                    format="YYYY/MM/DD HH:mm:ss" value-format="x" />
                                <span>至</span>
                                <el-date-picker v-model="ruleForm.gmtEnd" type="datetime" placeholder="选择日期"
                                    format="YYYY/MM/DD HH:mm:ss" value-format="x" />
                            </el-form-item>
                            <el-form-item label="团购基础人数" prop="minNum" label-width="150px">
                                <el-input-number v-model="ruleForm.minNum" :min="1" controls-position="right" />
                            </el-form-item>
                            <el-form-item label="活动结束时人数没有" label-width="150px">
                                <el-radio-group v-model="ruleForm.automaticRefund">
                                    <el-radio-button :label="0">不退货,我要发货</el-radio-button>
                                    <el-radio-button :label="1">自动退货,我不发货</el-radio-button>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="达到基础人数采取:" label-width="150px" />
                        </el-form>
                    </div>
                    <div class="conten-type">
                        <h4>商品类型(sku)</h4>
                        <el-popover v-model:visible="visibles" width="400px" placement="right" trigger="click">
                            <template #reference>
                                <el-button type="primary" plain>批量定价</el-button>
                            </template>
                            <template #default>
                                <div style="display: flex;align-items: center;padding: 0px 30px;">
                                    <div>团购价格</div>
                                    <el-input-number v-model="num" :min="1" controls-position="right"
                                        style="margin-left: 33px;margin-right: 5px;" />元
                                </div>
                                <div style="text-align: center;margin: 20px 0px;">
                                    <el-button @click="visibles = false">取消</el-button>
                                    <el-button type="primary" @click="hedlerCommodityprimary()">确定</el-button>
                                </div>
                            </template>
                        </el-popover>
                    </div>
                    <div>
                        <el-table :data="groupShopSkuList" style="width: 100%">
                            <el-table-column prop="id" label="skuID" align="center" width="80" />
                            <el-table-column prop="barCode" label="sku条形码" align="center" width="150" />
                            <el-table-column prop="title" label="类型名" align="center" width="150" />
                            <el-table-column prop="stock" label="库存" align="center" />
                            <el-table-column prop="price" label="现价/元" align="center" />
                            <el-table-column prop="skuGroupShopPrice" label="团购价格/元" align="center" />
                            <el-table-column label="操作" align="center">
                                <template #default="scope">
                                    <el-button type="primary" @click="toUpdate(scope.$index, scope.row)">更新</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <!-- 更新弹出框 -->
                        <el-dialog v-model="dialogFormVisible" title="更新团购价格">
                            <el-form :model="toUpdateList" require-asterisk-position="left" label-position="left">
                                <el-form-item label="团购价格" label-width="140px">
                                    <el-input-number v-model="toUpdateList.skuGroupShopPrice" class="mx-4" :min="1"
                                        controls-position="right" clearable />元
                                </el-form-item>
                                <el-form-item label="现价" label-width="140px">
                                    <span>{{ toUpdateList.presentPrice }}元</span>
                                </el-form-item>
                                <el-form-item label="sku类型名" label-width="140px">
                                    <span>{{ toUpdateList.skuTypeName }}</span>
                                </el-form-item>
                            </el-form>
                            <template #footer>
                                <span class="dialog-footer">
                                    <el-button @click="dialogFormVisible = false">取消</el-button>
                                    <el-button type="primary" @click="updateOk">确定</el-button>
                                </span>
                            </template>
                        </el-dialog>
                    </div>
                </el-drawer>
            </div>
        </div>
        <div>
            <Paging v-bind="pagingDatas" @page-change="pageChange"></Paging>
        </div>
        <el-backtop :right="100" :bottom="100" ref="main" target=".main" :visibility-height="20" />
    </div>
</template>
<script lang="ts" setup>
import { Search, Plus } from '@element-plus/icons-vue'
import { ref, reactive, nextTick, watch } from 'vue'
import { ClassPagination, ClassToUpdateList } from "#/index";
import { post } from "@/utils/http";
import Paging from "@/components/paging/Paging.vue";
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import '@/utils/dataFriend'
const ruleFormRef = ref<FormInstance>()
const visible = ref(false) //添加和编辑抽屉显示和隐藏
const visibles = ref(false) //批量定价气泡框显示和隐藏
let bool = ref(true) //用来判断是添加还是编辑
let num = ref(1) //批量定价
const dialogFormVisible = ref(false) //更新对话框显示和隐藏
let pagingDatas = reactive(new ClassPagination) //请求分页的数据
const options: TypeProductSku[] = reactive([]) //商品列表
const groupShopSkuList: TypeGroupShopSkuDTOList[] = reactive([]) //商品sku列表
const groupShopSkuDTOList: TypeGroupShopSkuDTOList[] = reactive([]) //团购sku列表
const tableData: TypeGroupPurchase[] = reactive([]) //团购列表
const props = {
    emitPath: false,
    value: 'id',
    label: 'label',
    children: 'children'
}
//搜索绑定的数据
const searchData = reactive({
    groupTitle: "",
    groupId: '',
    groupStatus: undefined
})
const toUpdateList = reactive(new ClassToUpdateList)//更新对话框数据
const main = ref()  //滚动组件对象的引用
const newSearchData = reactive({ ...searchData })
const groupStatus = reactive([
    {
        label: '冻结',
        value: 0
    },
    {
        label: '激活',
        value: 1
    },
    {
        label: '全部',
        value: ''
    }
])
const ruleForm = reactive({
    spuId: '',
    gmtStart: '',
    gmtEnd: '',
    minNum: 1,
    automaticRefund: 0,
    id: '',
})
const newRuleForm = reactive({ ...ruleForm })
const validatePass = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入内容'))
    }
    callback()
}
//结束时间验证
const validateGmtEnd = (rule: any, value: any, callback: any) => {
    if (value == '') {
        callback(new Error('请输入结束时间'))
    } else if (value < ruleForm.gmtStart) {
        callback(new Error("结束时间必须大于开始时间"))
    }
    callback()
}
const rules = reactive({
    spuId: [{ validator: validatePass, trigger: ['blur', "change"] }],
    gmtEnd: [{ validator: validateGmtEnd, trigger: ['blur', "change"] }],
    minNum: [{ validator: validatePass, trigger: ['blur', 'change'] }],
})
//加载团购列表
const loadGroupPurchaseList = () => {
    let data = {
        _gp: 'admin.groupshop',
        _mt: 'list',
        id: newSearchData.groupId,
        spuName: newSearchData.groupTitle,
        status: newSearchData.groupStatus,
        page: pagingDatas.page,
        limit: pagingDatas.limit
    }
    post(data).then(res => {
        console.log(res);
        let { errno, errmsg, data } = res
        if (200 == errno) {
            tableData.length = 0
            groupShopSkuDTOList.length = 0
            pagingDatas.total = data.total
            tableData.push(...data.items)
            tableData.forEach(item => {
                groupShopSkuDTOList.push(...item.groupShopSkuDTOList)
            })
        } else {
            ElMessage.error(errmsg)
        }
    })
}
loadGroupPurchaseList()

//函数式深度拷贝
function deepClone(obj: any, hash = new WeakMap()) {
    if (obj === null) return obj // 如果是null或者undefined我就不进行拷贝操作
    if (obj instanceof Date) return new Date(obj)
    if (obj instanceof RegExp) return new RegExp(obj)
    // 可能是对象或者普通的值  如果是函数的话是不需要深拷贝
    if (typeof obj !== 'object') return obj
    // 是对象的话就要进行深拷贝
    if (hash.get(obj)) return hash.get(obj)
    let cloneObj = new obj.constructor()
    // 找到的是所属类原型上的constructor,而原型上的 constructor指向的是当前类本身
    hash.set(obj, cloneObj)
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            // 实现一个递归拷贝
            cloneObj[key] = deepClone(obj[key], hash)
        }
    }
    return cloneObj
}


// function deepClone<T extends Array<T> | any>(sourceData: T): T { 
//      if (Array.isArray(sourceData)) { 
//          return sourceData.map(item => deepClone(item)) as T 
//      } 
//      const obj: T = {} as T 
//      for (let key in sourceData) { 
//          if ((typeof sourceData[key] === 'object') && sourceData[key] !== null) { 
//              obj[key] = deepClone(sourceData[key]) 
//          } else { 
//              obj[key] = sourceData[key] 
//          } 
//      } 
//      return obj 
//  } 


//商品sku列表
const loadGroupShopSkuList = () => {
    let data = {
        _gp: 'admin.product',
        _mt: 'detail',
        spuId: ruleForm.spuId
    }
    post(data).then(res => {
        console.log(res);
        let { errno, errmsg, data } = res
        if (200 == errno) {
            groupShopSkuList.length = 0
            groupShopSkuList.push(...data.skuList)
            groupShopSkuList.forEach(item => {
                item.skuId = item.id
            })
        } else {
            ElMessage.error(errmsg)
        }
    })
}

//商品列表
const loadProductSku = () => {
    let data = {
        _gp: 'admin.product',
        _mt: 'getSpuBigTree'
    }
    if (options.length == 0) {
        post(data).then(res => {
            console.log(res);
            let { errno, errmsg, data } = res
            if (200 == errno) {
                options.length = 0
                options.push(...data)
            } else {
                ElMessage.error(errmsg)
            }
        })
    }
}
loadProductSku()
//更新弹窗
const toUpdate = (index: number, row: TypeGroupShopSkuDTOList) => {
    dialogFormVisible.value = true
    toUpdateList.presentPrice = row.price
    toUpdateList.skuTypeName = row.title
    toUpdateList.skuGroupShopPrice = row.skuGroupShopPrice
    toUpdateList.index = index
}

//更新单个团购价格确定
const updateOk = () => {
    groupShopSkuList.some(item => {
        if (item.price < toUpdateList.skuGroupShopPrice) {
            return ElMessage.error('团购价不能大于现价')
        } else {
            groupShopSkuList[toUpdateList.index].skuGroupShopPrice = toUpdateList.skuGroupShopPrice
            dialogFormVisible.value = false
        }
    })
}

//添加弹窗
const handlerAddCoupon = () => {
    visible.value = true
    bool.value = true
    Object.assign(ruleForm, newRuleForm)
    groupShopSkuList.length = 0
    num.value = 1
}
//编辑弹窗
const handleEdit = (row: TypeGroupPurchase) => {
    console.log(row);
    visible.value = true
    bool.value = false
    Object.assign(ruleForm, row)
    groupShopSkuList.length = 0
    // let groupShopSkuLists = JSON.parse(JSON.stringify(row.groupShopSkuDTOList))
    let groupShopSkuLists = deepClone(row.groupShopSkuDTOList)
    groupShopSkuList.push(...groupShopSkuLists)
}
//对话框里的创建和编辑
const hedlerCreateAndEdit = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            let groupShopList = JSON.stringify(groupShopSkuList)
            let data = {
                _gp: 'admin.groupshop',
                _mt: bool.value == true ? 'create' : 'edit',
                ...ruleForm,
                groupShopSkuList: groupShopList
            }
            post(data).then(res => {
                console.log(res);
                let { errno, errmsg } = res
                if (200 == errno) {
                    visible.value = false
                    ElMessage.success(bool.value == true ? '添加成功' : '编辑成功')
                    loadGroupPurchaseList()
                } else {
                    ElMessage.error(errmsg)
                }
            })
        } else {
            console.log('error submit!')
            return false
        }
    })
}

//批量定价
const hedlerCommodityprimary = () => {
    groupShopSkuList.some(item => {
        if (item.price < num.value) {
            return ElMessage.error('团购价不能大于现价')
        } else {
            groupShopSkuList.map(item => item.skuGroupShopPrice = num.value)
            visibles.value = false
        }
    })
}
//删除
const handleDelete = (row: TypeGroupPurchase) => {
    let data = {
        _gp: 'admin.groupshop',
        _mt: 'delete',
        id: row.id
    }
    ElMessageBox.confirm(
        '请问是否删除',
        '消息提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }
    )
        .then(() => {
            post(data).then(res => {
                if (200 == res.errno) {
                    ElMessage.success('删除成功')
                    loadGroupPurchaseList()
                } else {
                    ElMessage.error(res.errmsg)
                }
            })

        })
        .catch(() => {
            ElMessage.info('取消操作')
        })
}


//查找
const handlerSearch = () => {
    Object.assign(newSearchData, searchData)
    pagingDatas.page = 1
    loadGroupPurchaseList()
}

//分页组件每次调用事件
function pageChange(e: TypePaGing) {
    pagingDatas.page = e._page
    pagingDatas.limit = e._limit
    loadGroupPurchaseList()
    nextTick(() => {
        main.value.$el.click?.()
    })
}
</script>
<style lang="less" scoped>
.main {
    >div {
        margin: 15px 0px;

        .el-input {
            width: 11vw;
        }
    }

    .conten {
        /deep/ .el-drawer__body {
            padding: 0px;
        }

        .conten-goodsSku {
            padding: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;

            .el-form {
                margin-top: 20px;

                /deep/ .el-form-item__label {
                    margin-left: 40px;
                }
            }
        }

        .conten-type {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #ccc;
            padding: 20px;
        }
    }

}
</style>